package cn.git.shiro.service.impl;

import cn.git.shiro.constant.ShiroJWTConstant;
import cn.git.shiro.entity.User;
import cn.git.shiro.result.Result;
import cn.git.shiro.service.UserService;
import cn.git.shiro.util.JWTUtil;
import cn.git.shiro.util.PassUtil;
import cn.git.shiro.util.RedisUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 用户登录serviceImpl
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-03-27
 */
@Service
public class UserServiceImpl implements UserService {

    /**
     * 模拟数据库密码
     */
    private static final String DB_PASSWORD = "$2a$10$a7nOTTarTPXrzEU4DTcHrOSS2NM7LLZpMWcnOYwcsaFqvRznsuPCe";

    @Autowired
    private PassUtil passUtil;

    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     */
    @Override
    public Result<String> login(String username, String password) {
        // 模拟用户登录
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setRoleId("1");

        // 校验加密后密码是否等于数据库查询出密码,DB_PASSWORD = passUtil.getPassHash(password)
        if (!passUtil.checkPass(password, DB_PASSWORD)) {
            throw new RuntimeException("登录失败!");
        }

        // 生成jwtToken信息
        Map<String, String> customClaimsMap = new HashMap<>();
        customClaimsMap.put("username", username);
        String jwtToken = jwtUtil.createJWTToken(username, customClaimsMap);

        // 将登录信息存储到redis中,1小时生效时间
        redisUtil.hset(ShiroJWTConstant.JWT_TOKEN_FLAG,
                jwtToken,
                JSONObject.toJSONString(user),
                ShiroJWTConstant.TIME_HOUR);

        return Result.ok(jwtToken);
    }

    /**
     * 登出
     *
     * @param jwtToken
     */
    @Override
    public void logout(String jwtToken) {
        if (ObjectUtil.isNotNull(redisUtil.hget(ShiroJWTConstant.JWT_TOKEN_FLAG, jwtToken))) {
            redisUtil.hdel(ShiroJWTConstant.JWT_TOKEN_FLAG, jwtToken);
        } else {
            throw new RuntimeException("传入token信息未获取到用户信息，登出失败!");
        }
    }

    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    @Override
    public User getUserById(String id) {
        User user = new User();
        user.setPassword(DB_PASSWORD);
        user.setId(id);
        user.setRoleId("1");
        user.setUsername("jack");
        return user;
    }
}
